﻿using Factory.Common;
using Factory.MasterData.WorkStations;
using Factory.MasterData.WorkStations.Dto;
using IronBarCode;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;
using VOL.WebApi;
using static IronSoftware.Drawing.AnyBitmap;


namespace Factory.Web.Controllers.MasterData
{
    /// <summary>
    /// 工作站控制器
    /// </summary>
    public class WorkStationController : Controller
    {
        /// <summary>
        /// 工作站服务
        /// </summary>

        private readonly IWorkStationAppService _workStationService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workStationService"></param>
        public WorkStationController(IWorkStationAppService workStationService)
        {
            _workStationService = workStationService;
        }

        #region 视图

        /// <summary>
        /// 工作站视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 工作站视图
        /// </summary>
        /// <returns></returns>
        public IActionResult AddView()
        {
            return View();
        }


        /// <summary>
        /// 工作站视图
        /// </summary>
        /// <returns></returns>
        public IActionResult HyperlinksView(int id)
        {
            ViewBag.id = id;
            return View();
        }

        /// <summary>
        /// 工作站视图
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateView(int id)
        {
            ViewBag.id = id;
            return View();
        }

        #endregion


        #region 接口

        /// <summary>
        /// 获取工作站（分页）
        /// </summary>
        /// <param name="workStationName">工作站名称</param>
        /// <param name="isNo">是否删除</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetWorkStationData(string? workStationName, int isNo, int page, int limit)
        {
            var pagedResult =await _workStationService.GetWorkStationShow(workStationName, isNo, page, limit);
            return Json(new { data = pagedResult, code = 0 });
        }

        /// <summary>
        /// 获取一个JG开头的随机码
        /// </summary>
        /// <returns>返回一个JG开头的随机码</returns>
        [HttpGet]
        public JsonResult CodeRandom()
        {
            Random random = new Random();

            // 生成后四位随机数
            int randomNumber = random.Next(1000, 10000); // 生成1000到9999之间的随机数

            // 拼接“JG”和随机数
            string result = "JG" + randomNumber.ToString();

            return Json(new { code = 0, data = result });
        }


        /// <summary>
        /// 获取所有车间的信息
        /// </summary>
        /// <returns>返回所有车间的信息</returns>
        [HttpGet]
        public JsonResult WorkshopSetupsList()
        {
            var list = _workStationService.WorkshopSetupsList();
            return Json(new { code = 0, data = list });
        }


        /// <summary>
        /// 添加工作站
        /// </summary>
        /// <param name="workStation"></param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<JsonResult> AddWorkStation(WorkStation workStation)
        {
            var res=await _workStationService.AddWorkStation(workStation);
            return Json(new { code = res });

        }

        /// <summary>
        /// 获取车间具体数据
        /// </summary>
        /// <returns>获取车间具体数据</returns>
        [HttpGet]
        public async Task<WorkStation> SpecificData(int id)
        {
            var workstation = await _workStationService.SpecificData(id);
            return workstation;
        }


        /// <summary>
        /// 删除工作站
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> DeleteWorkStation(int id)
        {
            var row = await _workStationService.DeleteWorkStation(id);
            return row;
        }


        /// <summary>
        /// 修改工作站
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateWorkStation(WorkStationInputAddDto adddto)
        {
            var res =await _workStationService.UpdateWorkStation(adddto);
            return res;
        }



        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="generateQRCode"></param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]

        public async Task<int> CreateQRCode(WorkStation generateQRCode)
        {
            // 编码为Base64字符串
            string base64Encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(generateQRCode.Image));

            // 生成二维码
            GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(base64Encoded);
            string path = "D:\\BitterCandy\\factory\\Factory\\src\\Factory.Web\\wwwroot\\qrcode";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // 生成唯一的文件名
            string uniqueFileName = $"qrcode_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid()}.jpg";

            string filePath = Path.Combine(path, uniqueFileName);
            barcode.SaveAsPng(filePath);
            // 保存二维码为PNG文件

            // 构建图像URL
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{uniqueFileName}";

            //string url= QiNiu.QiNiuUploadFile(imageUrl); // 上传到七牛云

            // 将二维码信息和其他数据保存到数据库


            generateQRCode.Image = imageUrl;

            // 保存到数据库
            await _workStationService.AddWorkStation(generateQRCode); // 替换为您的DbContext和表名

            // 成功反馈
            return 1; // 替换为您的成功页面
        }



        /// <summary>
        /// 修改二维码
        /// </summary>
        /// <param name="generateQRCode"></param>
        /// <returns>返回受影响行数</returns>
        [HttpPost]
        public async Task<int> UpdateQRCode(WorkStationInputAddDto generateQRCode)
        {
            QiNiu.DeleteTheLocal(generateQRCode.Image);
            //QiNiu.QiNiuDeleteFile(generateQRCode.Image); // 删除原来的二维码

            // 编码为Base64字符串
            string base64Encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(generateQRCode.Image));

            // 生成二维码
            GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(base64Encoded);
            string path = "D:\\BitterCandy\\factory\\Factory\\src\\Factory.Web\\wwwroot\\qrcode";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // 生成唯一的文件名
            string uniqueFileName = $"qrcode_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid()}.jpg";

            string filePath = Path.Combine(path, uniqueFileName);
            barcode.SaveAsPng(filePath);
            // 保存二维码为PNG文件

            // 构建图像URL
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{uniqueFileName}";

            //string url= QiNiu.QiNiuUploadFile(imageUrl); // 上传到七牛云

            // 将二维码信息和其他数据保存到数据库


            generateQRCode.Image = imageUrl;

            // 保存到数据库
            await _workStationService.UpdateWorkStation(generateQRCode); // 替换为您的DbContext和表名

            // 成功反馈
            return 1; // 替换为您的成功页面
        }

        #endregion


    }
}
